package com.gjy.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-10 14:02:41
 */
public class IntegerAddDecoder extends ReplayingDecoder<IntegerAddDecoder.Phase> {

    private static final Logger logger = LoggerFactory.getLogger(IntegerAddDecoder.class);
    private Integer first;
    private Integer second;

    public IntegerAddDecoder() {
        super(Phase.PHASE_1);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        switch (state()) {
            case PHASE_1:
                first = in.readInt();
                checkpoint(Phase.PHASE_2);
                break;
            case PHASE_2:
                second = in.readInt();
                Integer sum = first + second;
                out.add(sum);
                checkpoint(Phase.PHASE_1);
                break;
            default:
                break;
        }
    }

    enum Phase {
        PHASE_1, PHASE_2
    }
}
